package com.cloud.wms.http.observer;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;

import com.cloud.core.widget.dialog.LoadingDialog;


/**
 * Created by Tanghaibo
 * 2018/3/22
 * description:
 */

public class ProgressDialogHandler extends Handler {
    public static final int SHOW_DIALOG = 0x110;

    public static final int DISMISS_DIALOG = 0x111;

    private LoadingDialog mDialog;

    private Context context;

    private boolean forceCanceled;

    private ProgressCancelListener mListener;

    public ProgressDialogHandler(Context context, boolean forceCanceled, ProgressCancelListener mListener) {
        super();
        this.context = context;
        this.forceCanceled = forceCanceled;
        this.mListener = mListener;
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case SHOW_DIALOG:
                showDialog();
                break;
            case DISMISS_DIALOG:
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                    mDialog = null;
                }
                break;
        }
    }

    /**
     * 显示loading dialog
     */
    private void showDialog() {
        if (mDialog == null) {
            mDialog = new LoadingDialog.Builder(context)
                    .setCancelable(forceCanceled)
                    .create();
            if (forceCanceled) {
                mDialog.setOnCancelListener(onCancelListenerImp);
            }
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
        }
    }


    private ProgressDialog.OnCancelListener onCancelListenerImp = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            mListener.dialogCanceled();
        }
    };
}
